<template>
  <div class="container">
    <div class="mb10">
      <div class="mb10">检索对话欢迎语：</div>
      <a-textarea v-model:value="welcomeMessage" placeholder="请输入检索对话欢迎语" :auto-size="{ minRows: 2, maxRows: 5 }"
        :disabled="!isWelcomeEditing" />
      <div class="flex-end mt10">
        <a-button type="primary" v-show="!isWelcomeEditing" @click="handleWelcomeEdit">修改</a-button>
        <a-button v-show="isWelcomeEditing" @click="handleCancelWelcome" type="secondary" class="mr10">取消</a-button>
        <a-button @click="handleConfirmWelcome" v-show="isWelcomeEditing" type="primary">确定</a-button>
      </div>
    </div>
    <div>
      <div class="mb10">文档解读欢迎语：</div>
      <a-textarea v-model:value="documentMessage" placeholder="请输入文档解读欢迎语" :auto-size="{ minRows: 2, maxRows: 5 }"
        :disabled="!isDocumentEditing" />
      <div class="flex-end mt10">
        <a-button type="primary" v-show="!isDocumentEditing" @click="handleDocumentEdit">修改</a-button>

        <a-button v-show="isDocumentEditing" @click="handleCancelDocument" type="secondary" class="mr10">取消</a-button>
        <a-button @click="handleConfirmDocument" v-show="isDocumentEditing" type="primary">确定</a-button>
      </div>
    </div>
    <div class="mb10">
      <div class="guideSetHeader">
        <div>首页引导设置</div>
        <a-button type="primary" @click="addGuide">新增引导</a-button>
      </div>
      <div class="guideList">
        <div v-for="(item, index) in guideList" :key="index" class="guideItemCard">
          <a-form ref="formRef" :model="item" @finish="e => onFinish(e, index)">
            <a-row>
              <a-col :span="8">
                <a-form-item :labelCol="labelCol" name="title" :rules="[{ required: true, message: '请输入标题' }]"
                  label="标题：">
                  <a-input v-model:value="item.title" :disabled="!item.isEdit" :maxlength="7" placeholder="请输入标题" />
                </a-form-item>
              </a-col>
              <a-col :span="14">
                <a-form-item :labelCol="labelCol" name="description"
                  label="描述：">
                  <a-input v-model:value="item.description" :disabled="!item.isEdit" :maxlength="30"
                    placeholder="请输入描述" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="welecomeContent" name="content" :rules="[{ required: true, message: '请输入欢迎语' }]"
              label="欢迎语：">
              <a-textarea v-model:value="item.content" :disabled="!item.isEdit" placeholder="请输入欢迎语" />
            </a-form-item>
            <a-row>
              <a-col :span="8">
                <a-form-item :labelCol="labelCol" name="seq" label="排序：" :rules="[{ required: true, message: '请输入排序' }]">
                  <a-input v-model:value="item.seq" :disabled="!item.isEdit" placeholder="请输入排序" v-integer-only />
                </a-form-item>
              </a-col>
              <a-col :span="14">
             
                <a-form-item :labelCol="labelCol" name="iconUrl"
                  label="图标：">
                  <!-- <a-input v-model:value="item.icon" placeholder="请输入排序" /> -->
                  <a-upload v-if="item.isEdit" v-model:file-list="fileList" name="file" :multiple="false" :max-count="1"
                    list-type="picture" accept=".png,.jpg,.jpeg" :custom-request="e => customUpload(e, item)" @remove="e =>removeFile(e,index)">
                    <img v-if="item.iconUrl" :src="item.iconUrl" alt="" style="width: 50px; height: 50px;margin-right: 20px;">
                    <a-button>
                      <upload-outlined></upload-outlined>
                      {{ item.iconUrl ? '重新上传' : '上传图标' }}
                    </a-button>
                  </a-upload>
                  <div v-else style="display: flex; align-items: center;">
                    <img v-if="item.iconUrl" :src="item.iconUrl" alt="" style="width: 50px; height: 50px;">
                    <div style="margin-left: 20px;">{{ item.iconName }}</div>
                  </div>

                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-item :labelCol="labelCol" name="questionType" label="问答类型：" :rules="[{ required: true, message: '请输入问答类型' }]">
                  <a-input  v-model:value="item.questionType" v-integer-only :disabled="!item.isEdit" placeholder="请输入问答类型"  />
                </a-form-item>
              </a-col>
            </a-row>
            <div class="guideItemFooter">
              <div class="isShowStatus">
                <a-form-item name="status" label="显示状态：">
                    <a-switch v-model:checked="item.status" :checked-value=1 :un-checked-value=0 @change="onFinish(item, index)" />
                </a-form-item>
              </div>
              <div class="opreateButton">
                <a-button type="primary" danger @click="deleteGuide(item, index)">删除本引导</a-button>
                <a-button v-if="!item.isEdit" type="primary" @click="editGuide(item, index)">编辑</a-button>
                <a-button v-if="item.isEdit" type="primary" html-type="submit">保存</a-button>
                <a-button v-if="item.isEdit" @click="cancleEditGuide(item, index)">取消</a-button>
              </div>
            </div>
          </a-form>
        </div>

      </div>
    </div>
  </div>
</template>



<script setup lang="ts">
import { message as msgHelper, Modal, type FormInstance, } from 'ant-design-vue'
import { apiCopilotWelcome, apiUpdateWelcome, apiCopilotWelcomeAdminList, apiRemoveWelcome } from '@/api/manage'
import { onMounted, ref, createVNode } from 'vue'
import { type GuideItem } from '@/api/type'
import { UploadOutlined } from '@ant-design/icons-vue';
import { apiUpload } from '@/api'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { vIntegerOnly } from '@/utils/index'
const formRef = ref<FormInstance[]>([])
const welcomeMessage = ref('')
const isWelcomeEditing = ref(false)
const guideList = ref<GuideItem[]>([])
const guideItem: GuideItem = { id: '', isEdit: true, title: '', description: '', iconName: '', iconUrl: '', status: 0, seq: '', type: 3,questionType:'' }
const labelCol = ref({ span: 5 })
const fileList = ref([])
let lastWelcomeMessage = ''
const handleWelcomeEdit = () => {
  isWelcomeEditing.value = true
  lastWelcomeMessage = welcomeMessage.value
}

const handleCancelWelcome = () => {
  isWelcomeEditing.value = false
  welcomeMessage.value = lastWelcomeMessage
}

const handleConfirmWelcome = async () => {
  isWelcomeEditing.value = false
  await apiUpdateWelcome({ type: 1, content: welcomeMessage.value })
  msgHelper.success('修改成功')
}

const documentMessage = ref('')
const isDocumentEditing = ref(false)
let lastDocumentMessage = ''
const handleDocumentEdit = () => {
  isDocumentEditing.value = true
  lastDocumentMessage = documentMessage.value
}

const handleCancelDocument = () => {
  isDocumentEditing.value = false
  documentMessage.value = lastDocumentMessage
}

const handleConfirmDocument = async () => {
  isDocumentEditing.value = false
  await apiUpdateWelcome({ type: 2, content: documentMessage.value })
  msgHelper.success('修改成功')
}

// 新增引导
const addGuide = async () => {
  if (guideList.value.length >= 8) return msgHelper.warn('最多添加8个引导')
  if (guideList.value.some((item) => item.isEdit)) return msgHelper.warn('请先保存当前引导')
  fileList.value = []
  guideList.value.unshift(JSON.parse(JSON.stringify(guideItem)))
}
const deleteGuide = async (data: GuideItem, index: number) => {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '是否要删除该引导',
    onOk() {
      if(data.id){
        apiRemoveWelcome(data).then(() => {
        msgHelper.success('删除成功')
        getList()
      })
      }else{
        guideList.value.shift()
      }


    },
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() { },
  });

  console.log('delete', data, index)
}
const cancleEditGuide = async (data: GuideItem, index: number) => {
  console.log('cancleEdit', data, index, formRef.value[0])
  if (data.id) {  
  guideList.value[index].isEdit = false
  } else {
    guideList.value.shift()
  }
  if(formRef.value &&  formRef.value[0]){
    formRef.value[0].clearValidate()
  }

}
const saveGuide = async (data: GuideItem, index: number) => {
  await apiUpdateWelcome(data)
  console.log('save', data, index)
}
const editGuide = async (data: GuideItem, index: number) => {
  guideList.value[index].isEdit = true
}
const onFinish = async (values: any, index: number) => {
  await apiUpdateWelcome(guideList.value[index])
  msgHelper.success('保存成功')
  getList()
}
const getList = async () => {
  apiCopilotWelcomeAdminList({ type: 3, pageNum: 1, pageSize: 8 }).then(({ data: { entity = {} } }) => {
    guideList.value = entity.rows || []
  })
}

const customUpload = async (e: { file: File; onSuccess: Function; onError: Function }, item: GuideItem) => {
  console.warn(e.file, 'e', item)
  try {
    const formData = ref(new FormData())
    formData.value.append('file', e.file)
    const {
      data: { entity }
    } = await apiUpload(formData.value)
    if (entity?.url) {
      item.iconName = e.file.name
      item.iconUrl = entity.url
      console.warn(item, guideList.value, 'item.icon')
      msgHelper.success('上传成功')
    }
    e.onSuccess(entity, e)
  } catch (error) {
    e.onError(error)
  }
}
const removeFile = async(file,index) =>{
   guideList.value[index].iconUrl = ''
}

onMounted(() => {
  apiCopilotWelcome({ type: 1 }).then(({ data: { entity = {} } }) => {
    welcomeMessage.value = entity?.content || ''
  })
  apiCopilotWelcome({ type: 2 }).then(({ data: { entity = {} } }) => {
    documentMessage.value = entity?.content || ''
  })
  getList()
})
</script>

<style lang="scss" scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}

.guideSetHeader {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.guideItemCard {
  padding: 20px;
  background: #fff;
  border-radius: 9px;
  margin-top: 20px;
}

.guideItemFooter {
  display: flex;
  justify-content: space-between;
}

/* .opreateButton {
  
} */
.opreateButton button {
  margin-left: 20px;
}

:deep.welecomeContent {
  .ant-form-item-label {
    width: 110px;
    justify-content: flex-end;
  }
}
</style>
